package weaver.generalledger.action;

import com.engine.budget.manager.InstructionChangeManager;
import com.engine.budget.manager.InstructionManager;
import com.engine.budget.util.VerifyUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;
import weaver.workflow.request.WorkflowRequestMessage;
import weaver.workflow.workflow.WorkflowComInfo;

import java.util.HashMap;
import java.util.Map;

/**
 * @author DY
 * @version 1.0
 * @date 2024/7/24 15:22
 * @description: 总账工单执行一般指令流程Action
 */
public class ZzgdExecuteInstrucitonAction extends BaseBean implements Action {



    //指令
    private String zl;


    public void setZl(String zl){
        this.zl=zl;
    }
    @Override
    public String execute(RequestInfo requestInfo) {


        //流程requestID
        String requestid = requestInfo.getRequestid();

        writeLog("执行一般指令流程Action,start...,requestid:" + requestid+",zl:"+zl);

        try {
            RequestManager requestManager = requestInfo.getRequestManager();

            User user = requestManager.getUser();

            String nowdate = TimeUtil.getCurrentDateString();
            String workflowid = requestInfo.getWorkflowid();
            String formId = (new WorkflowComInfo()).getFormId(workflowid);
            String tableName = getNameById(formId);
            //流程名称
            String flowTableName = requestManager.getBillTableName();

            JSONArray paramsArr = new JSONArray();
            String sql = "select ysxm,yskm,zhdw,ysqjn,je,bzydjh,zhdjh,yskzq,zhdjlx,bzr,lyxt,sm,tdrbm,szgs,jjsx,event from uf_yskzzjb where lylc = ? and lyywbm=? ";

            RecordSet rs = new RecordSet();
            rs.executeQuery(sql,requestid,tableName);
            RecordSet rs1 = new RecordSet();
            while (rs.next()) {

                JSONObject newData = new JSONObject();

                //预算项目	budgetItem
                String ysxm = Util.null2String(rs.getString("ysxm"));
               // ysxm=changeField(ysxm, "uf_ysxmdb", "id", "xmbm", rs1);
                ysxm=getTreeId(ysxm);
                newData.put("budgetItem",  ysxm);
                //预算科目	budgetAccount
                String yskm = Util.null2String(rs.getString("yskm"));
                newData.put("budgetAccount",  yskm);
//                执行单位	exeUnit
                String yszrzx = Util.null2String(rs.getString("zhdw"));
                newData.put("exeUnit",  yszrzx);
//                预算期间（年）	budgetPeriod
                String ysrzsj = Util.null2String(rs.getString("ysqjn"));
                String ysrzsjYear = ysrzsj.substring(0, 4);
                newData.put("budgetPeriod",  ysrzsjYear);
//                金额	amount
                String wsje = Util.null2String(rs.getString("je"));
                newData.put("amount",  wsje);
//                指令	instruction
                newData.put("instruction",  zl);
//                被占用单据号	occDocNo
                String lcbm =nullString(rs.getString("bzydjh"),requestid);
                newData.put("occDocNo", lcbm);
//                执行单据号	exeDocNo
                String exeDocNo = nullString(rs.getString("zhdjh"),requestid);
                newData.put("exeDocNo", exeDocNo);
//                预算控制期	budgetPostingPeriod
                String budgetPostingPeriod = Util.null2String(rs.getString("yskzq"));
                newData.put("budgetPostingPeriod", budgetPostingPeriod);
//                执行日期	executionDate
                newData.put("executionDate",  nowdate);
//                执行单据类型	exeDocType
                String exeDocType = Util.null2String(rs.getString("zhdjlx"));
                newData.put("exeDocType", exeDocType );
//                报账人	claimant
                String tdr = Util.null2String(rs.getString("bzr"));
                String workcode = changeField(tdr, "hrmresource", "id", "workcode", rs1);
                String lastname = changeField(tdr, "hrmresource", "id", "lastname", rs1);
                newData.put("claimant",  workcode+"-"+lastname);
//                来源系统	sourceSystem
                String lyxt = Util.null2String(rs.getString("lyxt"));
                newData.put("sourceSystem",  lyxt);
//                说明	remark
                String zy = Util.null2String(rs.getString("sm"));
                newData.put("remark",  zy);
//                报账部门	reimbursementDept
                String tdrbm = Util.null2String(rs.getString("tdrbm"));
                String departmentcode = changeField(tdrbm, "hrmdepartment", "id", "departmentcode", rs1);
                String departmentname = changeField(tdrbm, "hrmdepartment", "id", "departmentname", rs1);
                newData.put("reimbursementDept",  departmentcode+"-"+departmentname);
//                报账公司	reimbursementCompany
                String szgs = Util.null2String(rs.getString("szgs"));
                String subcompanycode = changeField(szgs, "hrmsubcompany", "id", "subcompanycode", rs1);
                String subcompanyname = changeField(szgs, "hrmsubcompany", "id", "subcompanyname", rs1);

                newData.put("reimbursementCompany", subcompanycode+"-"+subcompanyname);
//                经济事项	economicEvent
                String jjsx = Util.null2String(rs.getString("jjsx"));
                jjsx=getTreeId(jjsx);
                //String bm = changeField(jjsx, "uf_jccs_jjsx", "id", "bm", rs1);
                newData.put("economicEvent",  jjsx);
//                事项	event
                String event = Util.null2String(rs.getString("event"));
                newData.put("event",  event);

                paramsArr.add(newData);

            }

            writeLog("执行一般指令流程Action,end...,paramsArr:" + paramsArr.toString());
            Map<String, Object> otherMap = new HashMap<>();
            otherMap.put("logId", requestid);
            otherMap.put("user", user);
            Map<String, Object> res = executeInstruction(paramsArr, otherMap);
            boolean res1 = (boolean) res.getOrDefault("res", false);
            writeLog("res--->"+res);
            if(!res1) {
                String message = res.getOrDefault("message", "").toString();
                //流程提交失败
                requestManager.setMessageid(WorkflowRequestMessage.WF_REQUEST_ERROR_CODE_07);
                //提示信息详细内容
                requestManager.setMessagecontent(message);
                return FAILURE_AND_CONTINUE;
            }


        }catch (Exception e) {
            writeLog("总账工单执行一般指令流程Action,异常...,requestid:" + requestid+",zl:"
                    +zl+",err:"+e.getMessage(), e);
        }

        writeLog("总账工单执行一般指令流程Action,end...,requestid:" + requestid+",zl:"+zl);
        return SUCCESS;

    }

    /**
     * 字段转换
     * @param value
     * @param tablename
     * @param oldField
     * @param newField
     * @param rs
     * @return
     */
    private String changeField(String value, String tablename, String oldField, String newField, RecordSet rs) {
        String sql = "select "+newField+" from "+tablename+" where "+oldField+" = ?";
        boolean b = rs.executeQuery(sql, Util.null2String(value));
        if(b && rs.next()) {
            return Util.null2String(rs.getString(1));
        }else {
            return "";
        }
    }

    /**
     * @param: paramsArr
    otherMap
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     * @description: 执行指令接口
    */
    public Map<String, Object>  executeInstruction(JSONArray paramsArr, Map<String, Object> otherMap) {
        writeLog("executeInstruction--->paramsArr:"+paramsArr);
        writeLog("executeInstruction--->otherMap:"+otherMap);

        //返回数据
        Map<String, Object> result = new HashMap();

        String logId = otherMap.getOrDefault("logId", "").toString();
        RecordSetTrans rsTrans = new RecordSetTrans();
        try {
            //返回数据数组
            JSONArray resArray = new JSONArray();

            RecordSet rs = new RecordSet();

            String sql = "select sfxrdb from uf_djkzclb where zhdjh = ?";

            for (int i = 0; i < paramsArr.size(); i++) {

                JSONObject data = paramsArr.getJSONObject(i);

                //执行单据号
                String exeDocNo = Util.null2String(data.getOrDefault("exeDocNo", ""));
                rs.executeQuery(sql, exeDocNo);
                if(rs.next()) {
                    otherMap.put("whiteZxdjh", "1");
                }else {
                    otherMap.put("whiteZxdjh", "0");
                }
                writeLog("Zzgd  data----发。>"+data);
                Map<String, Object> checkMap = VerifyUtil.verifyParams(data, otherMap, rs);
                otherMap.remove("whiteZxdjh");
                String status = Util.null2String(checkMap.getOrDefault("status", ""));
                if(!"1".equals(status) && !"-11".equals(status)) {
                    result.put("res", false);
                    result.put("message", "流程明细第"+(i+1)+"行预算指令失败，"+checkMap.getOrDefault("errorMessage",""));
                    return result;
                }
                resArray.add(checkMap);
            }
            writeLog("校验完成执行 paramsArr---》"+paramsArr.toString());

            InstructionManager instructionManager = new InstructionManager();

            JSONArray newResArray = new JSONArray();
            for (int i = 0; i < paramsArr.size(); i++) {

                JSONObject data = paramsArr.getJSONObject(i);
                writeLog("执行 data---》"+data.toString());
                //执行单据号
                String exeDocNo = Util.null2String(data.getOrDefault("exeDocNo", ""));
                //是否写入数据
                String sfxrdb = "";
                rs.executeQuery(sql, exeDocNo);
                if(rs.next()) {
                    sfxrdb= Util.null2String(rs.getString("sfxrdb"));
                }

                JSONObject yzData = resArray.getJSONObject(i);

                String status = Util.null2String(yzData.getOrDefault("status", ""));
                if(!"-11".equals(status) && !"1".equals(sfxrdb)) {
                    Map<String, Object> resMap = instructionManager.execute(data, otherMap, rsTrans);
                    JSONObject resdata = yzData.getJSONObject("data");
                    resMap.put("data", resdata);
                    yzData = JSONObject.fromObject(resMap);
                    String status1 = resMap.getOrDefault("status", "").toString();
                    writeLog("status1--->"+status1);
                    writeLog("resMap--->"+resMap.toString());
                    if(!"0".equals(status1)) {
                        result.put("res", false);
                        result.put("message",  "流程明细第"+(i+1)+"行预算指令失败，"+resMap.getOrDefault("errorMessage",""));
                        return result;
                    }
                }
                newResArray.add(yzData);

            }

            rsTrans.commit();
            for (int i = 0; i < paramsArr.size(); i++) {

                JSONObject data = paramsArr.getJSONObject(i);
                JSONObject yzData = newResArray.getJSONObject(i);
                InstructionManager.addInstructionLog(data, yzData, rs);

                InstructionChangeManager instructionChangeManager=new InstructionChangeManager();
                instructionChangeManager.YSZXChange(data.getString("budgetItem"));
                instructionChangeManager.YSXMChange(data.getString("budgetItem"));
                instructionChangeManager.YSSXChange(data.getString("economicEvent"));

            }



            result.put("res", true);
            result.put("message", "success");
            return result;
        }catch (Exception e) {
            rsTrans.rollback();
            result.put("res", false);
            result.put("message", "Action执行指令——异常");
            writeLog("logID:"+logId+",总账工单执行一般指令流程Action执行指令——异常...err:"+e.getMessage(), e);
        }

        return result;
    }
    public static String getNameById(String var0) {
        RecordSet var1 = new RecordSet();
        String var2 = "";
        String var3 = "select tablename from workflow_bill where id=?";
        var1.executeQuery(var3, new Object[]{var0});
        if (var1.next()) {
            var2 = var1.getString("tablename");
        }

        return var2;
    }
    private String getTreeId (String val) {
        try{
            String[] split = val.split("_");
            int length = split.length;
            return split[length-1];
        }catch (Exception e) {
            return val;
        }
    }

    public static String nullString(String var0,String requestid) {
        return var0 == null ? requestid : var0;
    }
}
